package com.siyu.rehearsal.grpc;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

public class CSVTimeReplacer {

    public static void updateCtrlCsv(String startTimeStr,String endTimeStr,String originalFilePath,String updatedFilePath) {


        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        LocalDateTime startTime = LocalDateTime.parse(startTimeStr, formatter);
        LocalDateTime endTime = LocalDateTime.parse(endTimeStr, formatter);

        Map<Integer, String> replacementMap = new HashMap<>();
        replacementMap.put(37, String.valueOf(startTime.getYear())); // Yr_beg
        replacementMap.put(38, String.format("%02d", startTime.getMonthValue())); // Mth_beg
        replacementMap.put(39, String.format("%02d", startTime.getDayOfMonth())); // D_beg
        replacementMap.put(40, String.format("%02d", startTime.getHour())); // Hr_beg
        replacementMap.put(41, String.format("%02d", startTime.getMinute())); // Min_beg
        replacementMap.put(42, String.valueOf(endTime.getYear())); // Yr_end
        replacementMap.put(43, String.format("%02d", endTime.getMonthValue())); // Mth_end
        replacementMap.put(44, String.format("%02d", endTime.getDayOfMonth())); // D_end
        replacementMap.put(45, String.format("%02d", endTime.getHour())); // Hr_end
        replacementMap.put(46, String.format("%02d", endTime.getMinute())); // Min_end

        try (BufferedReader br = Files.newBufferedReader(Paths.get(originalFilePath));
             BufferedWriter bw = Files.newBufferedWriter(Paths.get(updatedFilePath))) {
            String line;
            int lineNumber = 0;
            while ((line = br.readLine()) != null) {
                ++lineNumber;
                String[] parts = line.split(",");
                if (replacementMap.containsKey(lineNumber)) {
                    // 替换指定行的Value列
                    bw.write(lineNumber + "," + parts[1] + "," + replacementMap.get(lineNumber) + "\n");
                } else {
                    bw.write(line + "\n");
                }
            }
            System.out.println("CSV文件已成功更新并保存至：" + updatedFilePath);
        } catch (IOException e) {
            System.err.println("处理CSV文件时发生错误：" + e.getMessage());
        }
    }
}